package com.shitou.springai1.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shitou.springai1.admin.entity.dto.CommentDto;
import com.shitou.springai1.admin.entity.dto.LikeDto;
import com.shitou.springai1.admin.entity.dto.PostDto;
import com.shitou.springai1.admin.entity.dto.UserDto;
import com.shitou.springai1.admin.mapper.CommentMapper;
import com.shitou.springai1.admin.mapper.LikeMapper;
import com.shitou.springai1.admin.mapper.PostMapper;
import com.shitou.springai1.admin.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/forum")
public class ForumController {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private UserMapper userMapper;

    // 获取论坛帖子列表
    @GetMapping("/posts")
    public Map<String, Object> getPosts(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<PostDto> postPage = new Page<>(page, pageSize);
        QueryWrapper<PostDto> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1) // 只显示已发布的帖子
               .orderByDesc("create_time");
        IPage<PostDto> posts = postMapper.selectPage(postPage, wrapper);

        // 获取用户信息
        List<PostDto> postList = posts.getRecords();
        for (PostDto post : postList) {
            UserDto user = userMapper.selectOne(new QueryWrapper<UserDto>().eq("stu_or_tea_id", post.getStuOrTeaId()));
            if (user != null) {
                post.setNickName(user.getNickName());
                post.setImageUrl(user.getImageUrl());
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("posts", postList);
        result.put("total", posts.getTotal());
        result.put("current", posts.getCurrent());
        result.put("size", posts.getSize());
        return result;
    }

    // 发布帖子
    @PostMapping("/post")
    public Map<String, Object> createPost(@RequestBody Map<String, String> body) {
        String content = body.get("content");
        String stuOrTeaId = body.get("stuOrTeaId");

        PostDto post = new PostDto();
        post.setStuOrTeaId(stuOrTeaId);
        post.setContent(content);
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setStatus(1); // 默认已发布
        post.setCreateTime(LocalDate.from(LocalDateTime.now()));

        postMapper.insert(post);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "发布成功");
        return result;
    }

    // 获取帖子评论
    @GetMapping("/comments")
    public List<Map<String, Object>> getComments(@RequestParam Long postId) {
        QueryWrapper<CommentDto> wrapper = new QueryWrapper<>();
        wrapper.eq("post_id", postId)
               .eq("status", 1)
               .orderByAsc("create_time");
        List<CommentDto> comments = commentMapper.selectList(wrapper);

        // 获取评论用户信息
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (CommentDto comment : comments) {
            Map<String, Object> commentMap = new HashMap<>();
            commentMap.put("comment", comment);

            UserDto user = userMapper.selectOne(new QueryWrapper<UserDto>().eq("stu_or_tea_id", comment.getStuOrTeaId()));
            if (user != null) {
                commentMap.put("nickName", user.getNickName());
                commentMap.put("imageUrl", user.getImageUrl());
            }
            resultList.add(commentMap);
        }
        return resultList;
    }

    // 发布评论
    @PostMapping("/comment")
    public Map<String, Object> createComment(@RequestBody Map<String, Object> body) {
        Long postId = Long.valueOf(body.get("postId").toString());
        String stuOrTeaId = (String) body.get("stuOrTeaId");
        String content = (String) body.get("content");
        Long parentId = body.get("parentId") == null ? null : Long.valueOf(body.get("parentId").toString());

        CommentDto comment = new CommentDto();
        comment.setPostId(postId);
        comment.setStuOrTeaId(stuOrTeaId);
        comment.setContent(content);
        comment.setParentId(parentId);
        comment.setStatus(1);
        comment.setCreateTime(LocalDateTime.now());

        commentMapper.insert(comment);

        // 更新帖子的评论数
        PostDto post = postMapper.selectById(postId);
        post.setCommentCount(post.getCommentCount() + 1);
        postMapper.updateById(post);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "评论成功");
        return result;
    }

    // 点赞帖子
    @PostMapping("/like")
    public Map<String, Object> likePost(@RequestBody Map<String, Object> body) {
        Long postId = Long.valueOf(body.get("postId").toString());
        String stuOrTeaId = (String) body.get("stuOrTeaId");

        // 检查是否已经点赞
        QueryWrapper<LikeDto> wrapper = new QueryWrapper<>();
        wrapper.eq("post_id", postId)
               .eq("stu_or_tea_id", stuOrTeaId);
        LikeDto existingLike = likeMapper.selectOne(wrapper);

        Map<String, Object> result = new HashMap<>();
        if (existingLike != null) {
            // 取消点赞
            likeMapper.deleteById(existingLike.getId());
            PostDto post = postMapper.selectById(postId);
            post.setLikeCount(Math.max(0, post.getLikeCount() - 1));
            postMapper.updateById(post);
            result.put("liked", false);
            result.put("message", "已取消点赞");
        } else {
            // 点赞
            LikeDto like = new LikeDto();
            like.setPostId(postId);
            like.setStuOrTeaId(stuOrTeaId);
            like.setCreateTime(LocalDateTime.now());
            likeMapper.insert(like);

            PostDto post = postMapper.selectById(postId);
            post.setLikeCount(post.getLikeCount() + 1);
            postMapper.updateById(post);
            result.put("liked", true);
            result.put("message", "点赞成功");
        }

        // 更新点赞数
        PostDto post = postMapper.selectById(postId);
        result.put("likeCount", post.getLikeCount());
        result.put("success", true);
        return result;
    }

    // 检查用户是否已点赞帖子
    @GetMapping("/isLiked")
    public Map<String, Object> isLiked(@RequestParam Long postId, @RequestParam String stuOrTeaId) {
        QueryWrapper<LikeDto> wrapper = new QueryWrapper<>();
        wrapper.eq("post_id", postId)
               .eq("stu_or_tea_id", stuOrTeaId);
        LikeDto like = likeMapper.selectOne(wrapper);

        Map<String, Object> result = new HashMap<>();
        result.put("liked", like != null);
        return result;
    }
}
